package com.share.util.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.share.common.result.ResponseResult;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 结果封装类
 */
public class ResponseUtils {
    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        // 其他配置
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    public static  <T> void result(HttpServletResponse response, ResponseResult<T> msg) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        byte[] bytes = objectMapper.writeValueAsString(msg).getBytes(StandardCharsets.UTF_8);
        response.setContentLength(bytes.length);
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(bytes);
        }
    }

    public static <T> void success(HttpServletResponse response, T data) throws IOException {
        result(response, ResponseResult.success(data));
    }

    public static void error(HttpServletResponse response, String message) throws IOException {
        result(response, ResponseResult.fail(message));
    }
}